import router from "../index";
import * as cnt from '@/management/utils/constant'

// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob("@/management/pages/**/*.vue");

/**
 * @description 初始化动态路由
 */
export const initDynamicRouter = async (store) => {
  // console.log(store);

  try {
    // 1.获取菜单列表 && 按钮权限列表
    await store.dispatch('layouts/getAuthMenuList');

    // 2.添加动态路由
    store.getters['layouts/flatMenuListGet'].forEach((item) => {
      // console.log(item);
      item?.children && delete item.children;
      if (item?.component && typeof item?.component == "string") {
        if (item?.meta?.roles && typeof item?.roles == "string") {
          item.meta.roles = cnt[item.meta.roles];
        }

        item.component = modules["/src/management/pages" + item.component + ".vue"];
        router.addRoute(item);
      }
    });
  } catch (error) {
    // 当按钮 || 菜单请求出错时，重定向到登陆页
    router.replace('/login');
    console.log(error);
    return Promise.reject(error);
  }
};
